package com.example.micrpay.controller;

import com.example.micrpay.service.KQService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.api.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.http.HttpRequest;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @description: TODO
 * @author: uu
 * @data: 2023/7/23 下午 02:44
 * @version: v1.0
 */

@CrossOrigin
@Controller
@RequestMapping("/kq")
public class KQController {
    @Resource
    private KQService kqService;

    /*接收支付充值的请求*/
    @GetMapping("/recharge")
    public String receFrontRechangeKQ(Integer uid, BigDecimal rechargeMoney, Model mode){
        String view = "err";
        try{
            if (uid != null && uid > 0 && rechargeMoney !=null && rechargeMoney.doubleValue() >0){
                // 1. 检查是否为有效用户
                User user = kqService.queryUse(uid);
                if (user != null){
                    // 创建快钱支付的表单
                    Map<String, String> map = kqService.generateFormDate(uid,user.getName(), user.getPhone(), rechargeMoney);
                    mode.addAllAttributes(map);
                    // 创建充值记录
                    boolean result = kqService.addChargeRecord(rechargeMoney, map);
                    if (result){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        long orderTimeStamp = sdf.parse(map.get("orderTime")).getTime();
                        // 将订单号放到redis中
                        kqService.addOrderIdToRedis(map.get("orderId"), orderTimeStamp);
                    }
                }
                // 提交支付页面给快钱
                view = "kqForm";
            }
        }catch (Exception e){

            e.printStackTrace();
        }


        return view;
    }


    @GetMapping("/notify")
    @ResponseBody
    /*接收快钱给商家的支付结果*/
    public String payResultNotify(HttpServletRequest request){
        kqService.kqNotify(request);
        return "<result>1</result><redirecturl>http://localhost:8080/</redirecturl>";
    }

    @GetMapping("/query")
    @ResponseBody
    /*补单，定时任务调用redis中还未处理的订单*/
    public String queryKQ(){
        kqService.handleQueryOrder();
        return null;
    }
}
